package com.qiaotongtianxia.loans.net;

import android.graphics.Bitmap;
import android.support.annotation.NonNull;

import com.apkfuns.logutils.LogUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.PostRequest;
import com.qiaotongtianxia.loans.bean.BaseBack;
import com.qiaotongtianxia.loans.functionInterface.IBaseRequest;
import com.qiaotongtianxia.loans.util.CommonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by lisen on 2017/11/10.
 *
 * @author lisen < 4533548588@qq.com >
 * 网络请求类（对okgo的封装）统一处理参数和回调结果
 */

public class Request {


    //用于将activity设置给okhttp
    private Object tag;
    private RequestTransaction requestTransaction;
    private IRequestView iRequestView;

    private String errorMsg = "-404";
    private int errorCode = -404;

    private String token;

    public Request(Object tag,IRequestView iRequestView) {
        this.tag = tag;
        this.iRequestView = iRequestView;
        requestTransaction = RequestTransaction.getInstance();
    }

    public void setToken(String token) {
        this.token = token;
    }

    /**
     * 下载文件
     * @param url
     * @param dir
     * @param fileName
     */
    public void downLoad(final String url, String dir, String fileName, final IBaseRequest<File> iBaseRequest){

        final List<String> urls = requestTransaction.getUrls();
        if (urls.size() == 0){
            iRequestView.onStartProgress();
        }
        boolean start = iRequestView.onStart();
        if (!start){
            iRequestView.onEnd();
            iBaseRequest.onRequestError(-505,"请检查网络链接");
            return;
        }
        urls.add(url);
        final PostRequest post = OkGo.post(url);
        post.tag(tag);
        post.params("token",token);

        LogUtils.i(tag.getClass().getSimpleName()+" ,sendPost : ----> "+ post.getUrl()
                +"\n"+"参数 -----> "+ post.getParams().toString());

        post.execute(new FileCallback(dir,fileName) {
            @Override
            public void onSuccess(File file, Call call, Response response) {
                requestEnd(urls, url);
                iBaseRequest.onRequestSuccess(file);
            }
            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                requestEnd(urls, url);
                if (response != null){
                    errorCode = response.code();
                    errorMsg = response.message();
                }
                LogUtils.e(" = "+errorCode+" : "+errorMsg);
                iBaseRequest.onRequestError(errorCode,errorMsg);
            }

            @Override
            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
            }
        });
    }

    public void reqImg(final String url, TreeMap<String,Object> map, final IBaseRequest<Bitmap> iBaseRequest){
        final List<String> urls = requestTransaction.getUrls();
        if (urls.size() == 0){
            iRequestView.onStartProgress();
        }
        boolean start = iRequestView.onStart();
        if (!start){
            iRequestView.onEnd();
            iBaseRequest.onRequestError(-505,"请检查网络链接");
            return;
        }
        urls.add(url);
        final PostRequest post = OkGo.post(url);
        post.tag(tag);
        setParams(post,map);
        
        post.execute(new BitmapCallback() {
            @Override
            public void onSuccess(Bitmap bitmap, Call call, Response response) {
                requestEnd(urls, url);
                iBaseRequest.onRequestSuccess(bitmap);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                requestEnd(urls, url);
                if (response != null){
                    errorCode = response.code();
                    errorMsg = response.message();
                }
                LogUtils.e(" = "+errorCode+" : "+errorMsg);
                iBaseRequest.onRequestError(errorCode,errorMsg);
            }
        });
        
    }

    /**
     *  上传图片
     * @param url
     * @param map
     * @param aRequstCall
     */
    public void upload(final String url, TreeMap<String,Object> map, final ARequstCall aRequstCall){

        final List<String> urls = requestTransaction.getUrls();
        if (urls.size() == 0){
            iRequestView.onStartProgress();
        }
        boolean start = iRequestView.onStart();
        if (!start){
            iRequestView.onEnd();
            aRequstCall.onFailedCall(-505,"请检查网络链接");
            return;
        }
        urls.add(url);

        PostRequest post = OkGo.post(url);
        post.tag(tag);

        if (map != null && !map.isEmpty()){
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                Object obj = entry.getValue();
                if (obj instanceof File){
                    post.params(entry.getKey(), (File) obj);
                }else {
                    post.params(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
        }
        post.params("token",token);
        LogUtils.i(tag.getClass().getSimpleName()+" upload : ----> "+ url
                +"\n"+"upload 参数 -----> "+ post.getParams().toString());

        post.execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.e(LogForJson.warp(s));

                requestEnd(urls, url);
                BaseBack baseBack = handResult(s);
                parseResult(baseBack, aRequstCall);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                requestEnd(urls, url);
                if (response != null){
                    errorCode = response.code();
                    errorMsg = response.message();
                }
                LogUtils.e(" = "+errorCode+" : "+errorMsg);
                aRequstCall.onFailedCall(errorCode,errorMsg);
            }
        });

    }

    /**
     * post请求
     * @param url
     * @param map 参数
     * @param aRequstCall 回调
     */
    public void sendPost(final String url, TreeMap<String,Object> map, final ARequstCall aRequstCall){

        final List<String> urls = requestTransaction.getUrls();
        if (urls.size() == 0){
            iRequestView.onStartProgress();
        }
        boolean start = iRequestView.onStart();
        if (!start){
            iRequestView.onEnd();
            aRequstCall.onFailedCall(-505,"请检查网络链接");
            return;
        }
        urls.add(url);

        final PostRequest post = OkGo.post(url);
        post.tag(tag);
        setParams(post,map);
        post.execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.e(LogForJson.warp(s));

                requestEnd(urls, url);
                BaseBack baseBack = handResult(s);
                parseResult(baseBack, aRequstCall);

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);

                requestEnd(urls, url);
                if (response != null){
                    errorCode = response.code();
                    errorMsg = response.message();
                }
                LogUtils.e(" = "+errorCode+" : "+errorMsg);
                aRequstCall.onFailedCall(errorCode,errorMsg);
            }
        });
    }
    private void setParams(PostRequest post,TreeMap<String,Object> map){
        if (map != null && !map.isEmpty()){
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                post.params(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        post.params("token",token);
        LogUtils.i(tag.getClass().getSimpleName()+" ,sendPost : ----> "+ post.getUrl()
                +"\n"+"参数 -----> "+ post.getParams().toString());
    }
    /**
     * get请求
     * @param url
     * @param map
     */

    public void sendGet(final String url, TreeMap<String ,Object> map, final ARequstCall aRequstCall){

        final List<String> urls = requestTransaction.getUrls();
        if (urls.size() == 0){
            iRequestView.onStartProgress();
        }
        boolean start = iRequestView.onStart();
        if (!start){
            iRequestView.onEnd();
            aRequstCall.onFailedCall(-505,"请检查网络链接");
            return;
        }
        String resultUrl = url+genGetParams(map);
        urls.add(resultUrl);

        LogUtils.i(tag.getClass().getName()+" sendGet : ----> "+ resultUrl);

        OkGo.get(resultUrl).tag(tag).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.e(LogForJson.warp(s));

                requestEnd(urls, url);
                BaseBack baseBack = handResult(s);
                parseResult(baseBack, aRequstCall);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);

                requestEnd(urls, url);
                if (response != null){
                    errorCode = response.code();
                    errorMsg = response.message();
                }
                LogUtils.e(" = "+errorCode+" : "+errorMsg);
                aRequstCall.onFailedCall(errorCode,errorMsg);
            }
        });
    }
    private String genGetParams(TreeMap<String ,Object> map){
        if (map == null){
            return "";
        }
        if (!map.isEmpty()){
            StringBuilder strBuilder = new StringBuilder();
            for (String key : map.keySet()) {
                Object value = map.get(key);
                if ( value != null && value != "") {
                    strBuilder.append("&");
                    strBuilder.append(key);
                    strBuilder.append("=");
                    strBuilder.append(java.net.URLEncoder.encode(value+""));
                }
            }
            strBuilder.append("&");
            strBuilder.append("token");
            strBuilder.append("=");
            strBuilder.append(token);
            String params = strBuilder.toString().substring(1);
            LogUtils.e(map.toString());
            return "&" + params ;
        }
        return "";
    }
    @NonNull
    private BaseBack handResult(String s) {
        BaseBack baseBack = new BaseBack();
        JSONObject json = null;
        try {
            json = new JSONObject(s);
            baseBack.setCode(json.optString("code"));
            baseBack.setMsg(json.optString("msg"));
            baseBack.setData(json.getString("data"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return baseBack;
    }

    /**
     * 请求结束
     * @param urls
     * @param url
     */
    private void requestEnd(List<String> urls, String url) {
        urls.remove(url);
        if (urls.isEmpty()){
            iRequestView.onEnd();
        }
    }

    private void parseResult(BaseBack baseBack,ARequstCall aRequstCall){
        String code = baseBack.getCode();
        switch (CommonUtils.parseInt(code)){
            case 0://请求成功
                aRequstCall.onSuccessCall(baseBack);
                break;
            default:
                aRequstCall.onFailedCall(-1,baseBack.getMsg());
                break;
        }
    }
}
